package com.itump.base.util.security;

import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.userdetails.User;

/**
 * SpringSecurity的工具类.
 * 
 */
public class SpringSecurityUtils {

	/**
	 * 取得当前用户的登录名,如果当前用户未登录则返回null.
	 */
	public static String getCurrentUserName() {
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		if (auth == null)return null;
		String username = auth.getName();
		if(username.indexOf(",")>0)username=username.substring(0,username.indexOf(","));
		return username;
	}
	/**
	 * 取得当前用户对应的权限.
	 */
	public static String getUserbyAuths() {
		String allAuths="";
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		if (auth == null)return "";
		GrantedAuthority[] grantedAuths =auth.getAuthorities();
	    if(grantedAuths.length>0){
	          for(int i=0;i<grantedAuths.length;i++){
	        	  allAuths+=grantedAuths[i]+";";
	          }
	      }
		return allAuths;
	}
	
	/**
	 * 取得当前用户,返回值为SpringSecurity的User类及其子类, 如果当前用户未登
		录则返回null.
	 */
	@SuppressWarnings("unchecked")
	public static <T extends User> T getCurrentUser() {
		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if (principal == null)
			return null;
		return (T) principal;
	}
}
